import React, { useCallback, useEffect, useState } from 'react';
import { useDispatch, useSelector} from 'react-redux';
import { Route, Routes, useNavigate } from 'react-router-dom';
import _ from 'underscore';
import Cookies from "js-cookie";
import PrivateRoute from '@/hooks/PrivateRoute';
import Loading from '@/components/Loading';
import { baseRouters, addDynamicRoute } from "@/router";
import { flatRoutes } from '@/utils/routeUtils';
import LayoutLoader from '@/layout';
import { NOTFOUND } from '@/config/url';
// import { getGrid } from '@/utils';
// import { validate } from '@/service';
// import { setUserInfo, setLoginOpen } from '@/reducers/main';
import { useTranslation } from 'react-i18next';

function Application(props) {
    const { t } = useTranslation();
    const initState = () => ({
        loading: true,
        routerTree: baseRouters,
        routers: flatRoutes(baseRouters),
    }),
        [state, setState] = useState(initState),
        userToken = Cookies.get('token'),
        userinfo = localStorage.getItem('userinfo'),
        dispatch = useDispatch();
    const navigate = useNavigate();
    const info = useSelector(store => store.main.userInfo);
    /**
     * 检查用户是否登录（也可以获取用户信息）
     *
     */
    const checkLogged = () => {
        let routes = state.routers || [],
            // {expire, user, token} = response?.data || {},
            authSource = [], // 后端返回的数据
            authRoutes = addDynamicRoute(authSource), // 这里需要传入后端返回的数据
            appRoutes = flatRoutes(routes.concat(authRoutes)), // 应用的所有路由
            routerTree = baseRouters.concat(authSource); // 原始路由数据

        window.SITE_CONFIG['appRouterTree'] = routerTree;
        window.SITE_CONFIG['appRouteArray'] = appRoutes;
        setState(o => ({
            ...o,
            loading: false,
            routers: appRoutes,
            routerTree,
        }));
    };

    /**
     * 监听页面宽度变化
     *
     */
    // const resizeListen = useCallback(() => {
    //     let grid = getGrid();
    //     // dispatch(setStore({
    //     //     grid,
    //     //     isMobile: isMobileApp(grid),
    //     //     isPad: isPadApp(grid),
    //     //     isPc: isPcApp(grid),
    //     // }));
    // }, []);

    // 这是入口文件，页面间切换不会触发，只有应用首次加载时才会触发
    useEffect(() => {
        if (!userToken) {
            navigate('/login');
        }
        // 判断是否登录
        checkLogged(); // 有单独的校验是否登录接口通过检验
        // 先执行一次屏幕宽度计算
        // resizeListen();
        // 监听页面宽度变化，节流
        // const handleResize = _.throttle(resizeListen, 200);
        // window.addEventListener('resize', handleResize, false);
        // return () => {
        //     window.removeEventListener('resize', handleResize, false);
        // }
    }, []);
    return (
        <>
            {state.loading ? (
                <Loading tip={t('common.loading.tipTwo')} />
            ) : (
                <LayoutLoader routerTree={state.routerTree || []}>
                    <Routes>
                        {(state.routers || []).map(item => (
                            <Route
                                key={item.url}
                                path={item.url}
                                element={<PrivateRoute element={item.component} />}
                            />
                        ))}
                        <Route
                            path="*"
                            element={<PrivateRoute element={baseRouters.find(i => i.url === NOTFOUND)?.component || null} />}
                        />
                    </Routes>
                </LayoutLoader>
            )}
        </>
    );
}

export default Application;


